package com.by.controller;

import com.by.common.bean.ResultBean;
import com.by.common.exception.ValidateException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public abstract class BaseController {

    private final int SUCCESS = 200;  //代表成功
    private final int FAIL = 0; //代表失败

    protected ResultBean success(String msg) {
        return new ResultBean(SUCCESS, msg, null);
    }


    protected ResultBean success(String msg, Object data) {
        return new ResultBean(SUCCESS, msg, data);
    }

    protected ResultBean fail(String msg) {
        return new ResultBean(FAIL, msg, null);
    }

    protected ResultBean fail(String msg, Object data) {
        return new ResultBean(FAIL, msg, data);
    }


    /**
     * 后端验证
     *
     * @param result
     * @return map  如果没有错误信息 返回值为null
     */
    protected Map validate(BindingResult result) {
        //获取验证错误信息
        List<FieldError> errorList = result.getFieldErrors();
        Map map = null;
        //判断是否验证通过
        if (null != errorList && errorList.size() > 0) {
            map = new HashMap<>();
            Iterator<FieldError> it = errorList.iterator();
            while (it.hasNext()) {
                FieldError error = it.next();
                map.put(error.getField(), error.getDefaultMessage());
            }
        }
        return map;
    }


    /**
     * 后端自动验证  如果有错误信息 抛出异常  交由全局异常处理
     */
    protected void autoValidate(BindingResult result) throws ValidateException {
        //获取验证错误信息
        List<FieldError> errorList = result.getFieldErrors();
        Map map = null;
        //判断是否验证通过
        if (null != errorList && errorList.size() > 0) {
            map = new HashMap<>();
            Iterator<FieldError> it = errorList.iterator();
            while (it.hasNext()) {
                FieldError error = it.next();
                map.put(error.getField(), error.getDefaultMessage());
            }

            //抛出自定义异常
            throw new ValidateException(map);
        }

    }
}
